﻿#region Copyright and License
/*==============================================================================
 *  Copyright (c) www.51mvc.com Corporation.  All rights reserved.
 * ===============================================================================
 * This code and information is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the implied warranties
 * of merchantability and fitness for a particular purpose.
 * ===============================================================================
 * Licensed under the GNU General Public License (GPL) v2
 * http://www.51mvc.com/
 * Create By 小鱼(Leven)  - http://leven.com.cn
 * ==============================================================================*/
#endregion
using System;
using System.Collections.Generic;

namespace Infancy.Core.Cache {
    public class HttpCache : ICache {
        private static readonly System.Web.Caching.Cache cache = System.Web.HttpContext.Current.Cache;
        private static readonly object lockObject = new object();
        #region ICache Members

        public void Insert<T>(string key, T obj) {
            Insert(key, (object)obj);
        }

        public void Insert<T>(string key, T obj, TimeSpan ts) {
            Insert(key, obj, ts);
        }

        public void Insert(string key, object obj) {
            cache.Insert(key,
                obj,
                null,
                System.Web.Caching.Cache.NoAbsoluteExpiration,
                System.Web.Caching.Cache.NoSlidingExpiration,
                null);
        }

        public void Insert(string key, object obj, TimeSpan ts) {
            cache.Insert(key,
                obj,
                null,
                System.Web.Caching.Cache.NoAbsoluteExpiration,
                ts,
                null);
        }

        public bool Contains(string key) {
            return cache.Get(key) != null ? true : false;
        }

        public T Get<T>(string key) {
            return (T)Get(key);
        }

        public object Get(string key) {
            return cache.Get(key);
        }

        public object this[string key] {
            get { return Get(key); }
        }

        public void Remove(string key) {
            cache.Remove(key);
        }

        public void Clear() {
            System.Collections.IDictionaryEnumerator e = cache.GetEnumerator();
            IList<string> keyList = new List<string>();
            lock (lockObject) {
                while (e.MoveNext()) {
                    keyList.Add(e.Key.ToString());
                }
            }
            foreach (string item in keyList) {
                Remove(item);
            }
        }

        #endregion

        #region IDisposable Members

        public void Dispose() {
            Clear();
        }

        #endregion
    }
}
